package com.desire.k23;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * @author desire
 */
public class Producer {

    public static final String EXCHANGE_TOPIC = "exchange-topic";

    public static final String ROUTING_KEY_QUICK_ORANGE_RABBIT = "quick.orange.rabbit";
    public static final String ROUTING_KEY_QUICK_ORANGE_FOX = "quick.orange.fox";
    public static final String ROUTING_KEY_LAZY_BROWN_FOX = "lazy.brown.fox";
    public static final String ROUTING_KEY_QUICK_BROWN_FOX = "quick.brown.fox";
    public static final String ROUTING_KEY_LAZY_ORANGE_MALE_RABBIT = "lazy.orange.male.rabbit";
    public static List<String> keys = null;

    static {
        keys = new ArrayList<>(5);
        keys.add(ROUTING_KEY_QUICK_ORANGE_RABBIT);
        keys.add(ROUTING_KEY_QUICK_ORANGE_FOX);
        keys.add(ROUTING_KEY_LAZY_BROWN_FOX);
        keys.add(ROUTING_KEY_QUICK_BROWN_FOX);
        keys.add(ROUTING_KEY_LAZY_ORANGE_MALE_RABBIT);
    }

    public static void main(String[] args) {
        // 1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置虚拟主机  默认是/
        factory.setVirtualHost("erp");
        //设置mq服务器地址  默认是localhost
        factory.setHost("116.63.151.50");
        factory.setUsername("admin");
        factory.setPassword("123");
        //mq服务器的端口号
        factory.setPort(5672);
        // 2、获取连接、通道
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 3、声明发送消息到哪个exchange 声明一个exchange，指定类型为topic。
            channel.exchangeDeclare(EXCHANGE_TOPIC, BuiltinExchangeType.TOPIC);
            // 4、发送消息
            int count = 1;
            for (String routingKey : keys) {
                String message = String.format("Topic信息, 路由键 = %s, count = %d", routingKey, count);
                count++;
                channel.basicPublish(EXCHANGE_TOPIC, routingKey, null, message.getBytes(StandardCharsets.UTF_8));
                System.out.println("发送信息: " + message);
                Thread.sleep(2000);
            }
        } catch (TimeoutException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
